/**
 * 权限管理
 */
Ext.onReady(function() {
	UserStore = Ext.extend(Ext.data.Store, {
				constructor : function() {
					UserStore.superclass.constructor.call(this, {
								reader : this.userReader,
								proxy : new Ext.data.HttpProxy({
											url : 'getUserRule.do',
											method : 'POST'
										})
							})
				},
				userReader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'data'
						}, [{
									name : 'userId'
								}, {
									name : 'userName'
								}, {
									name : 'realName'
								}, {
									name : 'orgId'
								}, {
									name : 'sex'
								}, {
									name : 'post'
								}, {
									name : 'title'
								}, {
									name : 'birthday'
								}, {
									name : 'orgName'
								}, {
									name : 'rules'
								}])
			});

	UserSearchTbar = Ext.extend(Ext.Toolbar, {
				constructor : function() {
					UserSearchTbar.superclass.constructor.call(this, {
								items : ['用户名称：', {
											xtype : 'textfield',
											name : 'username',
											width : 100
										}, '-', {
											text : "查询",
											iconCls : 'icon-search',
											tooltip : '查询记录',
											handler : this.onSerchClick,
											scope : this
										}]
							});
					this.addEvents('onSerchClick');
				},
				onSerchClick : function() {
					this.fireEvent('onSerchClick', this);
				}
			});
	UserSearchPanel = Ext.extend(Ext.form.FormPanel, {
				userSearchTbar : null,
				constructor : function() {
					this.userSearchTbar = new UserSearchTbar();
					UserSearchPanel.superclass.constructor.call(this, {
								defaultType : 'textfield',
								border : false,
								frame : false,
								items : [this.userSearchTbar]
							});
				}
			});
	// 功能栏
	UserBtn = Ext.extend(Ext.Toolbar, {
				constructor : function() {
					UserBtn.superclass.constructor.call(this, {
								items : [/*
											 * { text : '浏览', iconCls :
											 * 'icon-view', handler :
											 * this.onView, scope : this }, '-',
											 */{
											text : '添加',
											iconCls : 'icon-add',
											handler : this.onAdd,
											scope : this
										}, '-', {
											text : '修改',
											iconCls : 'icon-edit',
											handler : this.onEdit,
											scope : this
										}, '-', {
											text : '删除',
											iconCls : 'icon-remove',
											handler : this.onDelete,
											scope : this
										}]
							}), this.addEvents('onView');
					this.addEvents('onAdd');
					this.addEvents('onEdit');
					this.addEvents('onDelete');
				},
				onAdd : function() {
					this.fireEvent('onAdd', this);
				},
				onEdit : function() {
					this.fireEvent('onEdit', this);
				},
				onDelete : function() {
					this.fireEvent('onDelete', this);
				},
				onView : function() {
					this.fireEvent('onView', this);
				}
			});

	UserFormPanel = Ext.extend(Ext.form.FormPanel, {
		constructor : function(b) {
			Ext.applyIf(this, b);
			UserFormPanel.superclass.constructor.call(this, {
				height : 350,
				width : 600,
				frame : true,
				border : false,
				autoScroll : true,
				labelAlign : 'right',
				labelWidth : 80,
				url : 'saveUser.do',
				method : 'POST',
				items : [{
					layout : "column",
					border : false,
					items : [{
						columnWidth : .5,
						layout : "form",
						defaultType : 'textfield',
						border : false,
						items : [{
									name : "userId",
									inputType : "hidden"
								}, {
									fieldLabel : "登录名",
									enableKeyEvents : true,
									name : "userName",
									allowBlank : false,
									listeners : {
										'keyup' : function(com) {
											Ext.Ajax.request({
												url : 'isUserNameExit.do',
												params : {
													name : com.getValue()
												},
												method : "post",
												success : function(response) {
													var result = Ext
															.decode(response.responseText);
													if (result.success) {
														Ext.getCmp('submit')
																.enable();
													} else {
														Ext.ux.Toast.msg('信息提示','此用户名已存在!');
														Ext.getCmp('submit')
																.disable();
														com.focus();
														return;
													}

												},
												failure : function(form, action) {
													Ext.ux.Toast.msg('信息提示','此用户名已存在!');
													com.focus();
												}
											});
										}
									}
								}, {
									fieldLabel : "密码",
									inputType : 'password',
									name : 'password',
									allowBlank : false
								},{
								        xtype : 'combo',
										fieldLabel : '所属机构',
										hiddenName : 'orgId',
										mode : 'remote',
										triggerAction : 'all',
										store : new Ext.data.JsonStore({
										   url : 'health/deptList.do',
										   fields : ['text', 'value'],
										   root : 'data',
										   totalProperty : 'totalProperty'
										}),
										queryParam : 'deptName',
										minChars : 1,
										pageSize : 10,
										listWidth : 300,
										valueField : "value",
										allowBlank : false,
										displayField : 'text',
										listeners : {
											render : function(combo){
												if(this.flag){
													var orgId = this.record.get('orgId');
													var orgName = this.record.get('orgName');
													var Record = combo.getStore().recordType;
														var record = new Record();
							        					record.set("value",orgId);
							        					record.set("text",orgName);
							        					combo.getStore().add(record);
												}
											},
											scope : this
										}
								},{
								     fieldLabel : '出生日期',
						             xtype : 'datefield',
						             format : 'Y-m-d',
					 	             name : 'birthday'
								},{
								        fieldLabel : '职务',
					                    hiddenName : "post",
										xtype : 'combo',
										forceSelection : true, //用户不能自己输入,只能选择列表中有的记录 
										mode : "local",
										triggerAction : "all",
										store:new Ext.data.SimpleStore({
											fields : ["value","text"],
											data : [["正高","正高"],["副高","副高"],["中级","中级"],["师级/助理","师级/助理"],["士级","士级"],["待聘","待聘"]]
										}),
										valueField : "value",
										displayField : "text",
										allowBlank : false
								}]
					}, {
						columnWidth : .5,
						layout : "form",
						defaultType : 'textfield',
						border : false,
						items : [{
									fieldLabel : "真实姓名",
									name : 'realName',
									allowBlank : false
								}, {
									fieldLabel : "确认密码",
									inputType : 'password',
									name : 'repassword',
									allowBlank : false
								},{
								    fieldLabel : '性别',
									hiddenName : "sex",
									xtype : 'combo',
									forceSelection : true, //用户不能自己输入,只能选择列表中有的记录 
									mode : "local",
									triggerAction : "all",
									allowBlank : false,
									store:new Ext.data.SimpleStore({
										fields : ["value","text"],
										data : [["男","男"],["女","女"]]
									}),
									valueField : "value",
									displayField : "text",
									allowBlank : false
								},{
								        fieldLabel : '职称',
										hiddenName : "title",
										xtype : 'combo',
										allowBlank : false,
										forceSelection : true, //用户不能自己输入,只能选择列表中有的记录 
										mode : "local",
										triggerAction : "all",
										store:new Ext.data.SimpleStore({
											fields : ["value","text"],
											data : [["主任医师","主任医师"],["副主任医师","副主任医师"],["主治医师","主治医师"],
											["医师","医师"],["医士","医士"],["主任药师","主任药师"],["副主任药师","副主任药师"],
											["主管药师","主管药师"],["药师","药师"],["药士","药士"],["主任护师","主任护师"],
											["副主任护师","副主任护师"],["主管护师","主管护师"],["护师","护师"],["护士","护士"],
											["主任技师","主任技师"],["副主任技师","副主任技师"],["主管技师","主管技师"],["技师","技师"],["技士","技士"]]
										}),
										valueField : "value",
										displayField : "text"
								}]
					}]
				}]
			});
		}
	});
	CheckBoxGroup = Ext.extend(Ext.form.CheckboxGroup, {
				constructor : function() {
					CheckBoxGroup.superclass.constructor.call(this, {
								id : "rolecheck",
								columns : 3,
								fieldLabel : '选择角色',
								items : [{}]
							});
				}
			});
	UserWin = Ext.extend(Ext.Window, {
		userFormPanel : null,
		constructor : function(config) {
			this.userFormPanel = new UserFormPanel(config);
			UserWin.superclass.constructor.call(this, {
						width : 600,
						autoHeight : true,
						modal : true,
						layout : 'fit',
						buttonAlign : "center", // 按钮居中
						constrain : true,
						items : this.userFormPanel,
						buttons : [{
									text : '确定',
									id : 'submit',
									handler : this.onSubmitClick,
									scope : this
								}, {
									text : '取消',
									handler : function() {
										this.close();
									},
									scope : this
								}]
					});
			this.addEvents('submit');
		},
		reset : function() {
			this.userFormPanel.getForm().reset();
		},
		onSubmitClick : function() {
			if (this.userFormPanel.form.isValid())
				this.fireEvent('submit', this, this.userFormPanel);
			else
				Ext.Msg.alert('提示信息', "表单验证不通过");
		},
		load : function(_record) {

			var self = this;
			
			this.userFormPanel.getForm().load({
				url : 'loadUser.do?id=' + _record.get("userId"),
				waitMsg : '正在载入数据...',
				method : 'POST',
				success : function(form, action) {
					self.show();
				},
				failure : function(form, action) {
					var result = Ext.decode(action.response.responseText);
					var funcs = result.rules;
				    var checkboxgroup = new CheckBoxGroup()
					for (var i = 0; i < funcs.length; i++) {
						checkboxgroup.items[i] = new Ext.form.Checkbox({
									name : "rule" + i,
									boxLabel : funcs[i].ruleName.split(",")[0],
									inputValue : funcs[i].ruleId,
									checked : funcs[i].ruleName.split(",").length == 1 ? false : true
								});
						self.userFormPanel.add(checkboxgroup);
					}
					self.userFormPanel.findByType("textfield")[2].value = result.password;
					self.userFormPanel.findByType("textfield")[7].value = result.password;
					self.userFormPanel.getForm().loadRecord(_record);
			        self.show();
				}
			})
			/*this.userFormPanel.getForm().loadRecord(_record);
			self.show();*/
		}
	});
	AddUserWin = Ext.extend(UserWin, {
				title : '新增用户'
			});
	EditUserWin = Ext.extend(UserWin, {
				title : '修改用户'
			});

	UserGridPanel = Ext.extend(Ext.grid.GridPanel, {
		title : '▪ 您现在所在的位置：用户管理',
		userSearchPanel : null,
		userStore : null,
		userBtn : null,
		addUserWin : null,
		editUserWin : null,
		constructor : function() {
			this.userSearchPanel = new UserSearchPanel();
			this.userStore = new UserStore();
			this.userBtn = new UserBtn();
			// this.addUserWin = new AddUserWin();
			// this.editUserWin = new EditUserWin();
			UserGridPanel.superclass.constructor.call(this, {
						border : false,
						renderTo : Ext.getBody(),
						tbar : this.userSearchPanel,
						viewConfig : {
							forceFit : true
						},
						stripeRows : true,// 斑马线
						colModel : new Ext.grid.ColumnModel([this.userCSM, {
									// header : "id",
									sortable : true,
									hidden : true,
									width : 100,
									dataIndex : 'userId',
									align : 'center'
								}, {
									header : "用户名",
									width : 100,
									sortable : true,
									dataIndex : 'userName',
									align : 'center'
								}, {
									header : "真实姓名",
									width : 100,
									sortable : true,
									dataIndex : 'realName',
									align : 'center'
								}, {
									header : "所属机构",
									width : 100,
									sortable : true,
									dataIndex : 'orgName',
									align : 'center'
								}, {
									header : "性别",
									width : 100,
									sortable : true,
									dataIndex : 'sex',
									align : 'center'
								}, {
									header : "出生日期",
									width : 100,
									sortable : true,
									dataIndex : 'birthday',
									align : 'center'
								}, {
									header : "职务",
									width : 100,
									sortable : true,
									dataIndex : 'post',
									align : 'center'
								}, {
									header : "职称",
									width : 100,
									sortable : true,
									dataIndex : 'title',
									align : 'center'
								}, {
									header : "拥有角色",
									width : 100,
									sortable : true,
									dataIndex : 'rules',
									align : 'center'
								}]),
						sm : this.userCSM,
						store : this.userStore,
						bbar : new Ext.PagingToolbar({
									pageSize : 20,
									store : this.userStore,
									displayInfo : true,
									displayMsg : "显示第{0}-{1}条记录，一共{2}条记录",
									emptyMsg : "没有记录"
								}),
						listeners : {
							render : function() {
								this.userBtn.render(this.tbar);
								this.initLoad();
							}
						}
					});
			this.userSearchPanel.userSearchTbar.on('onSerchClick',
					this.loadList, this);
			this.userBtn.on('onAdd', this.onAdd, this);
			this.userBtn.on('onEdit', this.onEdit, this);
			this.userBtn.on('onDelete', this.onDelete, this);
			this.userBtn.on('onView', this.onView, this);

		},
		userCSM : new Ext.grid.CheckboxSelectionModel(),
		loadList : function() {
			var params = this.userSearchPanel.getForm().getValues();
			this.userStore.baseParams = {
				name : params.username
			}
			this.userStore.load({
						params : {
							start : 0,
							limit : 20
						}
					})
		},
		initLoad : function() {
			this.userStore.load({
						params : {
							start : 0,
							limit : 20
						}
					})
		},
		reLoad : function() {
			this.userStore.reload();
		},
		onAdd : function() {
			Ext.Ajax.request({
				url : "getRule.do",
				method : "POST",
				success : function(response, action) {
					this.addUserWin = new AddUserWin();
					this.addUserWin.on('submit', this.insertUpdateRecord, this);
					var result = Ext.decode(response.responseText);
					var checkboxgroup = new CheckBoxGroup()
					for (var i = 0; i < result.length; i++) {
						checkboxgroup.items[i] = new Ext.form.Checkbox({
									name : "rule" + i,
									boxLabel : result[i].ruleName,
									inputValue : result[i].ruleId,
									checked : false
								});
					}
					this.addUserWin.userFormPanel.add(checkboxgroup);
					this.addUserWin.show();
				},
				scope : this
			})

		},
		onEdit : function() {
			if (this.getSelectionModel().getCount() == 0) { // 一条都没选
				Ext.Msg.alert('信息提示', '您未选择任何记录，请选择要修改的记录!');
			} else if (this.getSelectionModel().getCount() > 1) {
				Ext.Msg.alert('信息提示', '您选择了多条记录，一次只能修改一条记录!');
			} else {
				var record = this.getSelectionModel().getSelected();
				var id = record.get("userId");
				this.editUserWin = new EditUserWin({flag : true,record : record});
				this.editUserWin.on('submit', this.insertUpdateRecord, this);
				this.editUserWin.load(record);
			}
		},
		onDelete : function() {
			if (this.getSelectionModel().getCount() == 0) { // 一条都没选
				Ext.Msg.alert('信息提示', '您未选择任何记录，请选择要删除的记录!');
			} else {
				var self = this;
				var record = this.getSelectionModel().getSelections();
				var ids = new Array(record.length);
				for (var i = 0; i < record.length; i++) {
					ids[i] = record[i].get('userId');
				}
				Ext.Msg.alert('删除确认', '您确认要删除记录吗？按是将删除选中的记录！', function(btn) {
							if (btn == 'no') {
								return;
							}
							self.del(ids);
						})
			}
		},
		del : function(ids) {
			var self = this;
			Ext.Ajax.request({
						url : 'delUser.do',
						params : {
							ids : ids
						},
						method : "post",
						success : function(response) {
							var result = eval('(' + response.responseText + ')');
							if (result.success) {
								self.reLoad();
							} else {
								Ext.Msg.alert('提示信息', result.msg);
							}
						},
						failure : function(form, action) {
							Ext.Msg.alert('提示信息', "删除信息失败！");
						}
					});
		},
		insertUpdateRecord : function(_win, _form) {
			var self = this;
			var params = _form.getForm().getValues();
			if (params.password != params.repassword) {
				Ext.Msg.alert('提示信息', "密码不符合！");
				return;
			}
			var checkboxs = Ext.getCmp('rolecheck');
			var checkedArray = [];
			for (var i = 0; i < checkboxs.items.length; i++) {
				var checkbox = checkboxs.items.items[i];
				if (checkbox.checked) {
					checkedArray.push(checkbox.inputValue)
				}
			}
			if (checkedArray.length == 0) {
				Ext.Msg.alert('提示信息', "请为该用户分配角色！");
				return;
			}
			params.checkedValue = checkedArray.toString();
			params.orgName = _form.findByType("combo")[0].getRawValue();
			_form.form.submit({
						params : params,
						waitTitle : "请稍等",
						waitMsg : "正在保存您的信息",
						success : function(form, action) {
							if (action.result.success) {
								_win.close();
								self.reLoad();
							}
						}
					});
		}
	});
	new Ext.Viewport({
				layout : 'fit',
				items : new UserGridPanel()
			})

});